At this point we have all of our supplies gathered and we know how they work. So far we know how to make variables and do some basic operations on them. We know a bit about containers and how we can use them to hold variables in various ways. Now how do we use these things to make the computer do our bidding? This notebook is all about logic; making decisions based on conditions(booleans). We will also cover soething called loops which let us do something over and over again with a few lines of code, or, and much more importantly, do something to each element in a container. Let's start with logic.
We want our computers to make decisions. Computers, however, only know how to ask one type of question: if (something is true) then (do something). To ask this question using code, we use the following format:
if (some condition):
#put code here
Where (some condition) must give a boolean, or true and false, answer. If the condition is not true, perhaps we want to do something else. To do that we follow this format:
if (some condition):
#code here happens if the condition is true
else:
#code here happens if condition is false
It is key to note that the code in the if-block is indented. This tells the computer that the code should only run if the condition is true. Let's take a look at some examples.
In [11]:
if (True):
print("This will always print")
else:
print("This will never print")
if (False):
print("This will never print")
else:
print("This will always print")
In [12]:
a = 4
b = 5
if (a<b):
print("Wow, a was less than b, what a surprise!")
if (a>b):
print("I knew that a was greater than b!")
else:
print("Wait, a was not greater than b???")
#What does a<b actually return?
print(a<b)
#Aha, it was just a boolean all along
In [14]:
la = [1,2,3,4,5,'a','b']
if(1 in la):
print('1 is in la')
else:
print('1 is not in la')
Let's say you want to check a different condition before just saying, "The first condition was false, let's do the else statement." We could just use a second if statement, but instead we have the else-if statement, elif. It allows us to check a second condition after the first one fails. Let us concrete this idea with an example.
In [15]:
#I love food, let's take a look in my fridge
fridge = ['bananas', 'apples', 'water', 'tortillas', 'cheese']
#I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese
if('pizza' in fridge):
print('Patrick ate pizza and was happy')
elif('tortillas' in fridge and 'cheese' in fridge):
print('Patrick didn\'t get his pizza, but he did get a quesadilla and is still happy!')
else:
print('Patrick is still hungry')
Let's revamp that example, but this time, I went out and bought a pizza.
In [16]:
#I love food, let's take a look in my fridge
fridge = ['bananas', 'apples', 'water', 'tortillas', 'cheese', 'pizza']
#I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese
if('pizza' in fridge):
print('Patrick ate pizza and was happy')
elif('tortillas' in fridge and 'cheese' in fridge):
print('Patrick didn\'t get his pizza, but he did get a quesadilla and is still happy!')
else:
print('Patrick is still hungry')
Notice that, although I had the fixings for a quesadilla in my fridge, I had pizza so I never needed to check for a tortilla and cheese. This illustrates the fact that elif wont run unless the if statements before it fails. Further, you can stack elif statements forever. Let's see that.
In [17]:
#I love food, let's take a look in my fridge
fridge = ['bananas', 'apples', 'water', 'tortillas', 'beer']
#I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese
if('pizza' in fridge):
print('Patrick ate pizza and was happy')
elif('tortillas' in fridge and 'cheese' in fridge):
print('Patrick didn\'t get his pizza, but he did get a quesadilla and is still happy!')
elif('beer' in fridge):
print('Patrick is still hungry, but he has beer so he is happy')
else:
print('Patrick is still hungry')
What will be the output of the following code sample:
if(2<4):
if(len([1,2,3])<=len(set([1,1,1,2,2,3,3,3]))):
print("This will certainly print")
elif(2>1):
print("Or will this print?")
else:
print("It's gotta be this one...")
else:
print("This won't print...or will it.")
"I feel like I'm doing this over and over again" -Your computer on loops. Wanna do something 10, 100, n times? Loops are your best friend! Want to loop through a list containing all of your data? Loops are your bestest friend! We will look at two different types of loops, while loops and for loops.
While loops will continue to loop until some condition is false. While loops follow the format:
while (some condition):
#some code here
While loops can go on forever if the condition is never false. This is not the end of the world and you won't crash your computer. To stop a cell that is running, you can click on the stop button in the Jupyter toolbar. Let's see what we can do with this.
In [4]:
t=15
while(t>0):
print("t-minus " + str(t))
t-=1
While loops are really good if you want to do something over and over again. Let's generate some fake data with this. I introduce here the range() function. This generates a list of numbers. Let's see briefly how it works.
In [10]:
# Let's make a list of numbers starting at zero and going to 99. range() by default uses a step size of 1
#so this will yield integers from 0 to 99
x = range(0,100)
print(x)
# Unfortunately range does some strange things and doesn't return a list, if you want a list, you already know how to convert it.
print(list(x))
In [16]:
y = []
x = 1
while(x<100):
y.append(x**5-27*x**2-2300*x**-1+x%(x+1))
x+=1
print(y)
So that was a cute example of how we can generate some data based on some equation. Later on, however, we will want to graph our data and this requires a second list for our x values. The while loop is cumbersome in the respect and so we now introduce the for loop.
A for loop will loop through any container element by element and conveniently place each element in a special new variable. The format of a for loop is as follows:
for (special variable name) in (container we are looping through):
#do some stuff with, or without, that special variable
The advantage of for loops is that you get each element of some list handed to you on a platter...er, in a variable. Our previous example of generating data now allows us to make a list for our x data and loop through that. Let's see that in action.
In [17]:
x = range(1,100) #Remember that this makes a list of integers from 1 to 99
y = []
for val in x: #val is our special variable here, it will take on the value of every element in x
print(val)
y.append(val**2+3*val)
print(y)
Again, a neat little example. The true power of for loops comes when we have lists that are not numerical. Let's make every string in a list uppercase.
In [18]:
words = ['i', 'am', 'sorry', 'dave', 'i', 'can\'t', 'do', 'that']
upperwords = []
for word in words: #remember that word will take on the value of every element of words
print(word)
upperwords.append(word.upper()) # to make a string uppercase, you can use the .upper() function.
print(upperwords)
We have one more special type of loop to cover. List comprehensions; a quick way to make a list in one line.
A list comprehension is essentially a for loop sandwiched into a list. The syntax for a list comprehension is as follows:
X = [(expression involving special variable) for (special variable) in (some list)]
For example, we want a list containing x^2 for x in [0,1,2,3,4,5,6,7,8,9,10], we can create this list by using:
Y = [x**2 for x in range(0,11)]
Does this actually work?
In [19]:
y = [x**2 for x in range(0,11)]
print(y)
What about something wierder?
In [22]:
print(words)
wordslength = [len(word) for word in words]
print(wordslength)
My god, it worked! Think of the possibilities! With these new tools we can do 90% of all programming we will ever do. Pretty neat huh. I would like to show you one more example of list comprehensions.
In [24]:
# I only want words with length less than 3
newwords = [word for word in words if len(word)<3]
print(newwords)
This is an incredibly powerful tool that you will use on ocassion, so keep it in your noggin somewhere.
In [ ]:
In [ ]:
In [ ]: